package org.example.likou150.array;

/*
* https://leetcode.cn/problems/longest-common-prefix/description/?envType=study-plan-v2&envId=top-interview-150
* */
public class LongestCommonPrefix {
    public static void main(String[] args) {
        LongestCommonPrefix longestCommonPrefix = new LongestCommonPrefix();
        String[] strs = new String[]{"aaa","aa","aaa"};
        System.out.println(longestCommonPrefix.longestCommonPrefix(strs));
    }

    public String longestCommonPrefix(String[] strs) {
        if(strs.length==1) return strs[0];

        String prefix = strs[0];
        for (int i = 1; i < strs.length; i++) {
            prefix = getPrefix(prefix, strs[i]);
            if("".equals(prefix)){
                return "";
            }
        }
        return prefix;
    }

    private String getPrefix(String s1, String s2) {
        int maxLength = Math.min(s1.length(), s2.length());
        int index=0;
        for (int i = 0; i < maxLength; i++) {
            if (s1.charAt(i) != s2.charAt(i)) {
                break;
            }
            index=i+1;
        }
        return s1.substring(0, index);
    }


//    public String longestCommonPrefix(String[] strs) {
//        String s = strs[0];
//        String maxPrefix="";
//        for (int i = 0; i < s.length(); i++) {
//            String substring = s.substring(0, i+1);
//            for(int j =1;j<strs.length;j++){
//                if(!strs[j].startsWith(substring)){
//                    return maxPrefix;
//                }
//            }
//            maxPrefix=substring;
//        }
//        return maxPrefix;
//    }
}
